<template>
  <div class="page">
    <tree-list
      :path="selectPath"
      show-search
      @folder-select="folderSelect"
      @file-select="fileSelect"
    ></tree-list>
    <div v-loading="loading" class="content-wrapper">
      <c-card v-if="selectPath" title="实时数据">
        <div class="search-row">
          <div class="item">
            <label>应用类型</label>
            <el-select v-model="status" size="small" @change="_getRealData">
              <el-option label="全部" :value="null"></el-option>
              <el-option v-for="(s, i) in statusList" :key="i" :value="s.value" :label="s.label"></el-option>
            </el-select>
          </div>
        </div>
        <div id="echarts-1" class="echarts" style="height:300px;"></div>
        <el-table :data="realData" style="width: 100%">
          <el-table-column width="50">
            <template v-slot="{row}">
              <input v-model="selections" type="checkbox" :value="row.pkid" />
            </template>
          </el-table-column>
          <el-table-column prop="deviceName" type="index" label="序号">
            <!-- <template v-slot="{$index}">{{ $index }}</template> -->
          </el-table-column>
          <el-table-column prop="name" label="变量名称" show-overflow-tooltip></el-table-column>
          <el-table-column prop="recTime" label="实时时间" show-overflow-tooltip></el-table-column>
          <el-table-column prop="rvalue" label="实时值"></el-table-column>
        </el-table>
      </c-card>
      <h3 v-else style="text-align: center; ">请先选择厂站...</h3>
    </div>
  </div>
</template>

<script>
import TreeList from "./components/TreeList";
import CCard from "@/components/CCard";
import echarts from "echarts";
import { parseTime } from "@/utils";
let timer = null;
let min = null;
let max = null;
export default {
  name: "RealData",
  components: {
    TreeList,
    CCard
  },
  data() {
    return {
      loading: false,
      realData: null,
      hisData: [],
      selectPath: [],
      status: null,
      statusList: [],
      selections: [],
      echarts: null
    };
  },
  beforeRouteUpdate(to, from, next) {
    if (to.fullPath !== from.fullPath) {
      this.selectPath = (to.query.path || "").split(",");
      this.selectPath.length > 0 &&
        this._getRealData(this.selectPath[this.selectPath.length - 1]);
    }
    if (this.selectPath && !this.echarts) {
      this.$nextTick(() => {
        this.echarts = echarts.init(document.getElementById("echarts-1"));
      });
    }
    next();
  },
  computed: {
    chartsData() {
      const ret = [];
      this.hisData.forEach(d => {
        if (!d) {
          return;
        }
        const data = d.data.filter(v => this.selections.indexOf(v.pkid) > -1);
        ret.push({ time: d.time, data: data });
      });
      return ret;
    },
    options() {
      let data = [];
      const xData = [];
      if (this.chartsData.length === 0) {
        return {
          legend: {},
          xAxis: {
            type: "category",
            data: []
          },
          yAxis: {
            type: "value"
          },
          series: []
        };
      }
      const temp = {};
      this.chartsData.forEach(d => {
        xData.push(d.time);
        this.selections.forEach(id => {
          const a = d.data.filter(e => e.pkid === id)[0];
          if (a) {
            if (min === null) {
              min = a.rvalue - a.rvalue * 0.05;
              max = a.rvalue * 1.05;
            } else {
              const mn = a.rvalue - a.rvalue * 0.05;
              const mx = a.rvalue * 1.05;
              min = mn < min ? mn : min;
              max = mx > max ? mx : max;
              // min = mn;
              // max = mx;
            }
            if (!temp[id]) {
              temp[id] = {
                name: a.name,
                type: "line",
                data: []
              };
            }
            temp[id].data.push(a.rvalue);
          }
        });
      });
      min = min && parseFloat(min.toFixed(2));
      max = max && parseFloat(max.toFixed(2));
      data = Object.keys(temp).map(id => temp[id]);
      return {
        legend: {
          top: 0,
          data: data
        },
        grid: {
          top: 20,
          left: 50,
          right: 20,
          bottom: 40
        },
        tooltip: {
          trigger: "axis"
        },
        xAxis: {
          type: "category",
          data: xData
        },
        yAxis: {
          type: "value",
          min: min || 0,
          max: max || 1
        },
        series: data
      };
    }
  },
  watch: {
    selections() {
      // this.echarts.clear();
      // this.hisData = [];
    }
  },
  async created() {
    const path = this.$route.query.path;
    this.selectPath = path && path.split(",");
    if (path) {
      this.$nextTick(async () => {
        this.echarts = echarts.init(document.getElementById("echarts-1"));
        path && (await this._getRealData());
      });
    }
    this.RuleType()
  },

  destroyed() {
    clearInterval(timer);
  },
  methods: {
    // 应用类型
    RuleType() {
      return this.$axios
        .get("fes/drop/queryRuleType")
        .then(res => {
          if (res.code === 1) {
            this.statusList = res.data
          }
        })
        .catch()
    },
    async _getRealData() {
      // this.loading = true;
      this.hisData = [];
      await this.getRealData(
        this.selectPath[this.selectPath.length - 1],
        this.status
      );
      // this.loading = false;
      this.selections = [];
      this.selections.push(this.realData[0].pkid);
      timer && clearInterval(timer);
      timer = setInterval(() => {
        this.getRealData(
          this.selectPath[this.selectPath.length - 1],
          this.status
        );
      }, 3000);
    },
    getRealData(id, status) {
      const params = {};
      status !== null && (params.variabletype = status);
      return this.$axios
        .get("svg/device/realdata/" + id, { params })
        .then(res => {
          const now = parseTime(new Date(), "{h}:{i}:{s}");
          if (res.code === 1) {
            this.realData = res.data;
            this.hisData.push({ time: now, data: res.data });
            if (this.hisData.length > 30) {
              this.hisData.shift();
            }
            min = null;
            max = null;
            this.echarts.setOption(this.options, true);
          } else {
            throw res.msg;
          }
        })
        .catch();
    },
    folderSelect(path) {
      // console.log("select folder:", path);
      // const urlPath = this.$route.path;
      // this.selectPath = path;
      // this.$router.push(urlPath + "?path=" + path.join(","));
    },
    fileSelect(path) {
      const urlPath = this.$route.path;
      this.selectPath = path;
      this.$router.push(urlPath + "?path=" + path.join(","));
    }
  }
};
</script>

<style lang="scss" scoped>
.page {
  height: 100%;
}
.tree {
  position: absolute;
  width: 275px;
  height: 100%;
  overflow-y: auto;
  background: #222c3c;
  box-sizing: border-box;
}
// .content-wrapper {
//   overflow-y: auto;
//   margin-left: 275px;
//   height: 100%;
// }
</style>
